package org.tony.common.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.tony.common.io.ResourcesHelper;

public final class XmlHelper
{

  public static final Document read(String path)
  {
    SAXReader reader = null;
    InputStream fis = null;
    Document doc = null;
    try
    {
      reader = new SAXReader();
      fis = ResourcesHelper.getResourceAsStream(path);
      doc = reader.read(fis);
    }
    catch (Exception e)
    {
    }
    finally
    {
      if (fis != null)
      {
        try
        {
          fis.close();
        }
        catch (IOException e)
        {
        }
      }
    }
    return doc;
  }

  public static final void write(String path, Document doc)
  {
    OutputFormat format = OutputFormat.createPrettyPrint();
    OutputStream fos = null;
    try
    {
      fos = new FileOutputStream(new File(ResourcesHelper.getResourceURI(path)));
      format.setEncoding("UTF-8");
      XMLWriter writer = new XMLWriter(fos, format);
      writer.write(doc);
    }
    catch (UnsupportedEncodingException e)
    {
      e.printStackTrace();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    finally
    {
      if (fos != null)
      {
        try
        {
          fos.close();
        }
        catch (IOException e)
        {
        }
      }
    }
  }
}
